/**
 * 
 */
package com.kexinde.wjifen.dao;

import java.util.List;

import com.kexinde.wjifen.model.User;
import com.kexinde.wjifen.util.CreateRandomNum;
import com.kexinde.wjifen.util.JdbcTemplate;
import com.kexinde.wjifen.util.PageUtils;
import com.kexinde.wjifen.vo.GiftDetailExchange;
import com.kexinde.wjifen.vo.PageInfo;
import com.kexinde.wjifen.vo.RegistUser;

/**
 * 商城礼品兑换记录数据库操作类
 * 
 * @author vincent
 * 
 */
public class GiftExchangeDao {
	
	/**
	 * 分页查询giftDetail页面中对应gift的兑换记录
	 * @param giftId
	 * @param pageInfo
	 * @return
	 * 返回GiftDetailExchange类集合
	 * @throws Exception
	 */
	public List<GiftDetailExchange> GiftDetailExchangeLogs(Long giftId,PageInfo pageInfo) throws Exception{
		String querySql = "SELECT id,userId,name,count,time,status FROM v_giftexchange " +
				"WHERE giftId=? ORDER BY time DESC LIMIT ?,?";
		String countSql = "SELECT COUNT(*) FROM v_giftexchange WHERE giftId=?";
			
		Object [] params1 = {giftId};
		PageUtils pageUtils = new PageUtils(countSql,params1);
		pageUtils.countRange(pageInfo.getCurrentPage(), pageInfo.getLineSize());
		
		pageInfo.setAmount(pageUtils.getAmount());
		pageInfo.setPageAmount(pageUtils.getPageAmount());
		
		Object [] params2 = {giftId,pageUtils.getFirst(),pageUtils.getMax()};
		
		return JdbcTemplate.queryList("com.kexinde.wjifen.vo.GiftDetailExchange", querySql, params2, 6);
	}

	
	/**
	 * 检查兑换记录id是否存在
	 * @param id 要检查的id
	 * @return 布尔值,存在返回true
	 */
	public boolean isIdExist(Long id) throws Exception{
		String sql = "SELECT COUNT(*) FROM tb_giftexchange WHERE id=?";
		Object [] params = {id};
		int result = JdbcTemplate.count(sql,params);
		return (result>=1)?true:false;
	}
	
	/**
	 * 生成兑换记录(未完善）
	 * @param regUser
	 * @return
	 * @throws Exception
	 */
	public boolean add(Long userId,Long giftId) throws Exception{
		//生成不重复的微号
		Long id = Long.parseLong(CreateRandomNum.create(15));
		//int times = 10;
		while(this.isIdExist(id)){
			id = Long.parseLong(CreateRandomNum.create(15));
		}
		Object[] params = new Object[8];
		String sql = "INSERT INTO tb_user(name,password,telNum,email,purview,imagePath,totalPoint,weiNum)"
				+ "values(?,?,?,?,?,?,?,?)";

		return JdbcTemplate.executeUpdate(sql, params);

	}
}
